package com.cats.template.sys.controller;

import com.cats.template.sys.aggservices.SysAggService;
import com.cats.template.sys.enums.ResponseEnum;
import com.cats.template.sys.pojo.dto.LonginInfoDto;
import com.cats.template.sys.pojo.dto.UserDto;
import com.cats.template.sys.utils.JwtUtils;
import com.cats.template.sys.utils.ResponseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author duxiaobo
 * @date 2021/9/103:07 下午
 */
@RestController
@RequestMapping("/oauth")
public class LoginController {

    @Autowired
    private SysAggService sysAggService;

    /**
     * 登录获取token
     * @param userName
     * @param password
     * @return
     */
    @PostMapping("/token")
    public ResponseVO<LonginInfoDto> login(@RequestParam("userName") String userName, @RequestParam("password") String password) {
        UserDto userDto = sysAggService.getUser(userName);
        if (Objects.isNull(userDto)) {
            return ResponseVO.error(ResponseEnum.USER_NOT_EXIST_ERROR);
        }
        if (userDto.getIsLock()) {
            return ResponseVO.error(ResponseEnum.USER_DISABLE_ERROR);
        }
        password = JwtUtils.encryptPassword(password, userDto.getSalt());
        UserDto user = sysAggService.getUser(userName, password);
        if (Objects.isNull(user)) {
            return ResponseVO.error(ResponseEnum.USERNAME_OR_PASSWORD_ERROR);
        }

        Map<String, String> tokenMap = new HashMap<>(2);
        tokenMap.put("userId", user.getId().toString());
        tokenMap.put("userName", user.getUserName());
        String token = JwtUtils.sign(tokenMap);

        LonginInfoDto longinInfoDto = new LonginInfoDto();
        longinInfoDto.setUserName(user.getUserName())
                .setAccessToken(token)
                .setExpire(JwtUtils.getExpire());
        return ResponseVO.success(longinInfoDto);
    }

    /**
     * 验证失败跳转接口
     * @param message
     * @return
     */
    @GetMapping("/noLogin")
    public ResponseVO noLogin(@RequestParam("message") String message) {
        return new ResponseVO(ResponseEnum.AUTHENTICATION_FAILURE.getCode(), message);
    }
}
